package org.web.webmock.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@Order(Integer.MIN_VALUE)
public class DbConfig {

    @Autowired
    private Environment environment;

    @Autowired
    private DataSource dataSource;

    /**
     * 设置hibernate属性配置
     * @return
     */
    private Properties hibernateProperties() {

        Properties properties = new Properties();
        switch (this.environment.getProperty("spring.datasource.db-type")) {
            case "derby":
                properties.setProperty("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
                break;
            default:
                properties.setProperty("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
                break;
        }
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        //properties.setProperty("hibernate.show_sql", environment.getProperty("spring.jpa.show-sql"));
        //根据需要配置
        return  properties;

    }

    /**
     * 配置SessionFactory会话工厂注入到spring容器
     * @return
     */
    @Bean
    @Order(Integer.MIN_VALUE)
    LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(this.dataSource);
        localSessionFactoryBean.setPackagesToScan(this.environment.getProperty("spring.persistence-layer.scan-package")); //dao与entity的公共包
        localSessionFactoryBean.setHibernateProperties(this.hibernateProperties());
        return localSessionFactoryBean;

    }
}
